package cn.com.callback

import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.apache.http.HttpEntity
import org.apache.http.HttpResponse
import org.apache.http.client.config.RequestConfig
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: 项目Token相关统一管理接口* @author: LJT*
 *
 */

public class apiFaxCancel implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiFaxCancel.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            log.warn("API被非法IP调用-Request Not Allow!");
            return "Request Not Allow!";
        }

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String result = "";

        String Sms_Guid = KHUtil.FastJsonNull(request.getParameter("Sms_Guid"));
        log.debug("原始Get请求参数:" + Sms_Guid);

        try {
            // 获取token
            JSONObject getTokenJson = JSONObject.fromObject(Util.doHttpGet(KHDBConfig.getAPIURL(eliteBean, "Local_Token"), "UTF-8", 12000, 0));
            String access_token = getTokenJson.getJSONObject("data").getString("access_token");
            log.debug("获取调用Token:" + access_token);

            String CancelURL = KHDBConfig.getAPIURL(eliteBean, "FAX-CancelURL")

            // 查找待发送任务
            List getallSelectSQL = eliteBean.chaxun_sql('''Select R2.faxid
                                      From Waterofffaxbatch R1
                                      Left Join Kh_Sw_Sendfax R2
                                        On R1.Sms_Guid = R2.Sms_Guid
                                     Where R2.faxid is not null and R2.faxid != '' and R1.Sms_Guid = \'''' + Sms_Guid + '''\'''', "dataSource");
            log.debug("SQL获取待发送数据量:" + getallSelectSQL.size());

            for (int i = 0; i < getallSelectSQL.size(); i++) {

                Map selectResultcm = getallSelectSQL.get(i);
                log.debug("当前待发送数据：" + selectResultcm.toString());

                String faxid = selectResultcm.get("faxid").toString();

                doFaxCancel(eliteBean, CancelURL, access_token, faxid);

            }


        } catch (Exception e) {
            log.error("接口处理异常", e);

        }

        return "1";
    }


    public static String doFaxCancel(EliteBean eliteBean, String url, String token, String faxid) {

        Map<String, String> headParams = new HashMap<String, String>();
        headParams.put("Content-Type", "application/x-www-form-urlencoded");

        Map<String, String> callParams = new HashMap<String, String>();
        callParams.put("token", token);
        callParams.put("faxid", faxid);

        String callBody = KHUtil.urlencode(callParams, "");

        HttpPost httppost = new HttpPost(url);
        if (headParams != null) {
            Iterator entries = headParams.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry entry = (Map.Entry) entries.next();
                String key = (String) entry.getKey();
                log.debug("key:" + key);
                String value = (String) entry.getValue();
                log.debug("value:" + value);
                httppost.addHeader(key, value);
            }
        }

        CloseableHttpClient httpClient = HttpClients.createDefault();

        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();//设置请求和传输超时间
        httppost.setConfig(requestConfig);

        StringEntity se = new StringEntity(callBody, "UTF-8");
        httppost.setEntity(se);
        HttpResponse httpResponse = httpClient.execute(httppost);
        HttpEntity httpEntity = httpResponse.getEntity();
        if (httpEntity != null) {
            String result = EntityUtils.toString(httpEntity);

            log.debug("doFaxCancel传真取消调用完成：" + result);

        }

        httpClient.close();

    }

}
